/**
 * @authors tanqichao
 * @date    2017-03-21 13:59:27
 * @module  广告数据
 */

import { Form, Row, Col, Input, Button, Select, Table, Radio, DatePicker, Pagination, Icon, Popover } from 'antd';
import RangePicker from '../../plugin/rangePicker';
import { pageSize } from '../../../constants';
import { AccessControl } from '../../../utils/common';
import PacketModal from './packetList';
import SummaryModal from './summaryData';
import React, { Component } from 'react';
import { createForm } from 'rc-form';
import Styles from './adData.less';
import { Link } from 'dva/router';
import { connect } from 'dva';
import 'moment/locale/zh-cn';
import moment from 'moment';

moment.locale('zh-cn');

const RadioButton = Radio.Button;
const RadioGroup = Radio.Group;
const Option = Select.Option;
const FormItem = Form.Item;

class SearchAdData extends Component {
	constructor(props) {
		super(props);
		this.state = {
			page: 1,
			planId: '',
			beginTime: moment().format('YYYY-MM-DD'),
			endTime: moment().format('YYYY-MM-DD'),
			visible: false,
			timeVisible: false,
			summaryVisible: false,
			summaryTimeVisible: false,
			searchParams: {},
		}
	}

	// 初始化
	componentDidMount = () => {
		this.search('pre')
  }

  // 分页
  handlePage = (page) => {
  	this.setState({
  		page: page
  	}, () => {
  		this.search();
  	})
  }

  // 切换时间
	handleRangePicker = (beginTime, endTime) => {
		this.setState({
			beginTime: moment(beginTime).format('YYYY-MM-DD'),
			endTime: moment(endTime).format('YYYY-MM-DD')
		}, () => {
			this.search();
		})
	}

  // 搜索
	search = (type) => {
		this.props.form.validateFields((err, values) => {
			let params = {
				companyName: values.companyName || '',
				planName: values.planName || '',
				beginTime: this.state.beginTime,
				endTime: this.state.endTime,
				mail: values.mail || '',
				page: this.state.page,
				pageSize: pageSize,
				type: values.type || ''
			};
			let adDataCheckParams = window.localStorage.getItem('adDataCheckParams');
			this.setState({
				searchParams: params
			})
			if(type === 'pre' && adDataCheckParams) {
				params = JSON.parse(adDataCheckParams);
				console.log(params)
				this.setStatusFun({
					companyName: params.companyName,
					planName: params.planName,
					type: params.type,
					mail: params.mail
				});
			}
			this.setLocalStorage("adDataCheckParams", JSON.stringify(params));
			console.log('%c%s', 'color: #04B894', 'params:' + JSON.stringify(params));
			this.props.dispatch({
				type: 'adData/fetch',
				payload: JSON.stringify(params)
			})
    });
	}
	setResetSearchForm = () => {
		let params = {
			companyName: '',
			planName: '',
			beginTime: this.state.beginTime,
			endTime: this.state.endTime,
			mail: '',
			page: this.state.page,
			pageSize: pageSize,
			type: ''
		};
			this.props.form.setFieldsValue({'companyName': ''});
			this.props.form.setFieldsValue({'planName': ''});
			this.props.form.setFieldsValue({'type': ''});
			this.props.form.setFieldsValue({'mail': ''});
		this.setLocalStorage("adListCheckParams", JSON.stringify(params));
		this.props.dispatch({
			type: 'adData/fetch',
			payload: JSON.stringify(params)
		})
		console.log(params)
	}
	setStatusFun = (params) => {
		for(let key in params) {
			let keyValue = '';
			if(params[key]) {
				keyValue = params[key];
			}
			if(key === 'companyName') {
				this.props.form.setFieldsValue({'companyName': keyValue});
			}
			if(key === 'planName') {
				this.props.form.setFieldsValue({'planName': keyValue});
			}
			if(key === 'type') {
				this.props.form.setFieldsValue({'type': keyValue});
			}
			if(key === 'mail'){
				this.props.form.setFieldsValue({'mail': keyValue});
			}
		}
	}
	setLocalStorage = (key, data) => {
		if(window.localStorage){
			let storage=window.localStorage;
			storage.setItem(key,data);
		}else {
			alert('该浏览器不支持localStorage');
		}
	}
 	showSummary = (type, beginTime, endTime , planId) => {
		let searchParams = this.state.searchParams;
		if(beginTime==='null') {
			beginTime = Date.now();
			endTime = Date.now();
		}
	 if(type === 'time') {
			this.props.dispatch({
				type: 'adData/summaryList',
				payload: JSON.stringify({
					companyName: searchParams.companyName,
					planName: searchParams.planName,
					mail: searchParams.mail,
					type: searchParams.type,
					beginTime: moment(beginTime).format('YYYY-MM-DD'),
					endTime: moment(endTime).format('YYYY-MM-DD')
				})
			});
			this.setState({
				summaryTimeVisible: true,
				planId: planId
			 });

		}else if(type === 'every') {
			this.props.dispatch({
				type: 'adData/summaryList',
				payload: JSON.stringify({
					companyName: searchParams.companyName,
					planName: searchParams.planName,
					mail: searchParams.mail,
					type: searchParams.type,
					planId: planId,
					beginTime: moment(beginTime).format('YYYY-MM-DD'),
					endTime: moment(endTime).format('YYYY-MM-DD')
				})
			});
			this.setState({
				summaryTimeVisible: true,
				planId: planId
			});
		}
	}
	// 创意列表
	fetchPacketList = (planId, beginTime, endTime, stTime) => {
		this.setState({
			planId: planId
		 });
		this.props.dispatch({
			type: 'adData/fetchPacket',
			payload: JSON.stringify({
				planId: planId,
				beginTime: moment(beginTime).format('YYYY-MM-DD'),
				endTime: moment(endTime).format('YYYY-MM-DD')
			})
		});
		if(stTime) {
			this.setState({
				timeVisible: true
			});
		}else {
			this.setState({ visible: true });
		}
	}
	downloadData = () => {
		window.location.href = `http://${window.location.host}/api/dsp/statistics/ad/plan/data/download?data=${encodeURIComponent(JSON.stringify(this.state.searchParams))}`
	}

	// 素材列表
	fetchMaterialList = (crGrpId, beginTime, endTime) => {
		this.props.dispatch({
			type: 'adData/fetchMaterial',
			payload: JSON.stringify({
				crGrpId: crGrpId,
				beginTime: beginTime,
				endTime: endTime
			})
		})
	}
	showFetchSwitch = (id) => {
		this.setState({
			planId: id
		})
	}
	// 关闭创意列表弹窗
	onClose = () => {
		this.setState({
			visible: false,
			timeVisible: false,
			summaryVisible: false,
			summaryTimeVisible: false
		})
	}

	// create
	createDom = () => {
		const { getFieldDecorator } = this.props.form;
		const pageConfig = {
			className: "ant-table-pagination",
      total: this.props.totalCount,
      onChange: this.handlePage,
      current: this.state.page,
      pageSize: pageSize
		};
		const fetchSwitchContent = (planId) => {
			return (
				<div>
					<p className={Styles.fetchFirstP} onClick={this.fetchPacketList.bind(this, planId, this.state.beginTime, this.state.endTime, false)}>创意包</p>
					<p className={Styles.fetchFirstP} onClick={this.showSummary.bind(this, 'every', 'null', 'null', planId)}>时段分析</p>
				</div>
			);
		}
		const columns = [{
		  title: '广告计划名称',
		  dataIndex: 'name',
		  key: 'name',
			render: (text, record) => {
		    return (
					<div className={Styles.showFetchSwitchBox}>
						<Popover placement="right" content={fetchSwitchContent(record.planId)} trigger="hover">
							{text}
			        <span className={Styles.plusIcon}><Icon type="plus-circle-o" /></span>
			      </Popover>
					</div>
		    )
		  }
		},{
		  title: '广告类型',
		  dataIndex: 'type',
		  key: 'type',
			render: (text, record) => {
				return text === 1 ? '互动广告' : '展示广告'
			}
		}, {
		  title: '客户公司名称',
		  dataIndex: 'companyName',
		  key: 'companyName',
		  render: (text, record) => {
		    return (
		      <Link to={`/page/manageCustomer?companyName=${record.companyName}`}>{text}</Link>
		    )
		  }
		},{
		  title: '时间',
		  dataIndex: 'time',
		  key: 'time',
		}, {
		  title: '曝光量（次）',
		  dataIndex: 'exposureCount',
		  key: 'exposureCount',
		}, {
		  title: '点击（次）',
		  dataIndex: 'clickCount',
		  key: 'clickCount',
		}, {
		  title: '点击率',
		  dataIndex: 'clickRate',
		  key: 'clickRate',
		}, {
		  title: '点击均价',
		  dataIndex: 'avgPrice',
		  key: 'avgPrice',
		}, {
		  title: '总消耗（元）',
		  dataIndex: 'consumeTotal',
		  key: 'consumeTotal',
		}];
		const permissionList = this.props.permissions;
		const stkey = 'mm23',
					summaryObj = this.props.summaryListMain[0];
		let stmm = [<Col key={stkey} span={11} className={Styles.footerCol}>汇总</Col>];
		for(let k in summaryObj){
			stmm.push(<Col key={k} span={2} className={Styles.footerCol}>{summaryObj[k]}</Col>);
		}
		const downLoadObj = AccessControl(permissionList, 'dsp_ad_data_export') ?
		(
			<Button type="primary" icon="download" className={Styles.downloadBtn} onClick={this.downloadData}></Button>
		):'';
		const stThree = stmm[3];
		stmm.splice(3,1);
		stmm.push(stThree);
		return (
			<Form layout="inline">
				<div className={Styles.search}>
					<Row>
						<Col span={24}>
							<FormItem colon={false} label="广告计划名称" className={Styles.mr45}>
								{getFieldDecorator('planName')(
									<Input placeholder="请输入广告计划名称" />
	        			)}
							</FormItem>
							<FormItem colon={false} label="客户注册邮箱" className={Styles.mr45}>
								{getFieldDecorator('mail')(
									<Input placeholder="请输入客户注册邮箱" />
		      			)}
							</FormItem>
							<Button type="primary" size="large" onClick={this.search} className={Styles.searchBtn}>查询</Button>
							<Button type="primary" size="large" onClick={this.setResetSearchForm} className={Styles.searchBtn}>重置</Button>
						</Col>
					</Row>
					<Row className={Styles.mt20}>
						<Col span={24}>
							<FormItem colon={false} label="客户公司名称" className={Styles.mr45}>
								{getFieldDecorator('companyName')(
									<Input placeholder="请输入客户公司名称" />
	        			)}
							</FormItem>
							<FormItem colon={false} label="广告类型">
								{getFieldDecorator('type', {
									initialValue: ''
								})(
									<Select>
										<Option value="">全部广告</Option>
			              <Option value="1">互动广告</Option>
			              <Option value="2">展示广告</Option>
			            </Select>
		            )}
							</FormItem>
						</Col>
					</Row>
				</div>
				<Row className={Styles.list}>
					<Col span={24} className={Styles.head}>
						<div className={Styles.timeFilter}>
							<RangePicker onComplete={this.handleRangePicker} />
						</div>
						{downLoadObj}
						<Button type="primary" className={Styles.summaryBtn} onClick={this.showSummary.bind(this, 'time')}>分时段汇总</Button>
					</Col>
					<Col span={24}>
						<Table
							rowKey={record => record.planId}
							dataSource={this.props.list}
							footer={() => stmm}
							pagination={pageConfig}
							columns={columns}
						/>
					</Col>
				</Row>
			</Form>
		)
	}

	render () {
		return (
			<div className={Styles.adData}>
				{this.createDom()}
				<PacketModal
					onClose={this.onClose}
					planId={this.state.planId}
					endTime={this.state.endTime}
					visible={this.state.visible}
					beginTime={this.state.beginTime}
					onComplete={this.fetchPacketList}
					packetList={this.props.packetList}
					materialList={this.props.materialList}
					timeList={this.props.packetList}
					timeVisible={this.state.timeVisible}
					onFetchMaterialList={this.fetchMaterialList}
					packetSummary={this.props.packetSummary}
				 />
				 <SummaryModal
					  onClose={this.onClose}
	 					planId={this.state.planId}
						onComplete={this.fetchPacketList}
	 					summaryVisible={this.state.summaryVisible}
						summaryList={this.props.summaryList}
						showSummary={this.showSummary}
						summaryTotlelist={this.props.summaryTotlelist}
						materialList={this.props.materialList}
						summaryTimeVisible={this.state.summaryTimeVisible}
						searchParams={this.state.searchParams}
						permissions={this.props.permissions}
				 />
			</div>
		)
	}
}

export default connect((state) => {
	const { permissions } = state.indexPage;
	const { list, packetList, materialList, totalCount, summaryList, summaryTotlelist, summaryListMain, packetSummary} = state.adData;
	return {
		list,
		totalCount,
		packetList,
		materialList,
		summaryList,
		summaryListMain,
		summaryTotlelist,
		packetSummary,
		permissions
	}
})(createForm({})(SearchAdData));
